package com.hk.dyeyuesystem;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.hk.dyeyuesystem.db.DBOpenHelper;
import com.hk.dyeyuesystem.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 管理员管理用户操作类
 */
public class UserAdminActivity extends AppCompatActivity {

//  Initialize Toast
    private Toast toast;
//    Initialize intent
    private Intent intent;

//    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    private ListView userAdminListView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_admin);
        userAdminListView = findViewById(R.id.user_admin_list_view);
        //        实例化
        dbOpenHelper = new DBOpenHelper(UserAdminActivity.this, "db_book_system", null, 1);
        /**
         * 查询出所有的用户信息并进行回显（不包含已登录的用户）
         */
        findAll();
//        列表添加事件
//        添加长按点击弹出选项框菜单
        userAdminListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作！");
                menu.add(0,0,0,"借阅记录");
                menu.add(0,1,0,"挂失记录");
            }
        });

    }

    /**
     * 查询所有用户信息,不包含当前登录用户自己
     */
    private void findAll() {
//        获取当前登录用户信息
        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (Objects.isNull(bundle) && bundle == null) {
//                添加一个弹出对话框
                AlertDialog alertDialog = new AlertDialog.Builder(UserAdminActivity.this).create();
//                设置提示
                alertDialog.setMessage("活着就是为了改变世界，难道还有其他原因吗？");
//                设置按钮
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        指向登录界面
                        intent = new Intent(UserAdminActivity.this,MainActivity.class);
                        startActivity(intent);
                    }
                });
//                显示对话框
                alertDialog.show();
                return;
            }
        }
//        提取出当前登录用户信息
        String loginName = (String) bundle.get("loginName");
        String loginAccount = (String) bundle.get("loginAccount");
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("ACCOUNT", null, "USERNAME IS NOT ? AND ACCOUNT IS NOT ?", new String[]{loginName, loginAccount}, null, null, null);
        List<Map<String,Object>> resultList = new ArrayList<>(20);
        while (cursor.moveToNext()) {
            Map<String,Object> map = new HashMap<>(20);
            String userName = cursor.getString(1);
            String phone = cursor.getString(2);
            Integer type = Integer.valueOf(cursor.getString(4));
            String typeString = type.equals(1) ? "管理员":"学生";
            String createTime = cursor.getString(5);
            map.put("userName",userName);
            map.put("account",phone);
            map.put("type",typeString);
            map.put("createTime",createTime);
            resultList.add(map);
        }
        // 判断是否具有除自身以外其他的用户
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast,UserAdminActivity.this,"暂时没有注册用户！");
            return;
        }
//        将返回的值显示在ListView列表中
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                UserAdminActivity.this,
                resultList,
                R.layout.user_list_layout,
                new String[]{"userName","account","type","createTime"},
                new int[]{R.id.username,R.id.account,R.id.user_type,R.id.register_time}
        );
        userAdminListView.setAdapter(simpleAdapter);

    }


    /**
     * 给菜单项添加事件
     * @param item 菜单索引
     * @return
     */
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
//        获取上下文
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        得到listView中选择的条目绑定的Id
        String id = String.valueOf(info.id);
//        得到列表子节点的视图
        View targetView = info.targetView;
        //                获取单列 某一元素的控制权
        TextView account = targetView.findViewById(R.id.account);
//                获取元素内容
        String accountToString = account.getText().toString();
        Log.i("=====ListView列表绑定的ID==",id);
        Log.i("===== 对应的账号 ==",accountToString);
//        创建数据库操作API实例
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        switch (item.getItemId()) {
            case 0:
                // TODO: 2021/12/19 完成事件操作（已完成）
//                查看借阅记录的方法
                queryBorrowDiaLog(accountToString,readableDatabase);
                return true;
            case 1:
//                查看挂失记录的方法
                queryLossDiaLog(accountToString,readableDatabase);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * 查询挂失记录
     * @param accountToString 账号 手机号
     * @param readableDatabase 数据库操作API
     */
    private void queryLossDiaLog(String accountToString, SQLiteDatabase readableDatabase) {
        intent = new Intent(UserAdminActivity.this, UserBorrowOrLossAdminActivity.class);
//        传递参数
        Bundle bundle = new Bundle();
        bundle.putString("account",accountToString);
        bundle.putString("operateStatus","2");
        intent.putExtras(bundle);
//        开启跳转
        startActivity(intent);
    }

    /**
     * 查询借阅记录
     * @param accountToString 账号 手机号
     * @param readableDatabase 数据库操作API
     */
    private void queryBorrowDiaLog(String accountToString, SQLiteDatabase readableDatabase) {
        intent = new Intent(UserAdminActivity.this, UserBorrowOrLossAdminActivity.class);
//        传递参数
        Bundle bundle = new Bundle();
        bundle.putString("account",accountToString);
        bundle.putString("operateStatus","1");
        intent.putExtras(bundle);
//        开启跳转
        startActivity(intent);
    }


    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}